package com.madsvillage.printersdk.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import com.madsvillage.printersdk.IPrinterConnection;

public class PrinterConnection implements IPrinterConnection{
	
	/*
	 * Time out for the printer connection in seconds
	 */
	private int timeout;
	/*
	 * connection check variable either connected or not
	 */
	private boolean isConnected;
	/*
	 * Socket for the printer
	 */
	private Socket printerSocket;
	/**
	 * Constructor for the printer connection 
	 * @param ctx for application context
	 */
	public PrinterConnection(){		
		timeout = 3;
	}
	
	/**
	 * This method connect the printer with the given ip address
	 * @param ip  Lan IP for the LAN printer
	 * @param port Port for the LAN printer usually 9100 is used for LAN Printer
	 * @return true if connect successfully otherwise false
	 * @throws IOException 
	 */
	@Override
	public boolean connect(String ip, int port) throws IOException {
		SocketAddress socketAddress = new InetSocketAddress(ip, port); 
		this.createSocket();
		connect(socketAddress);		
		
		return isConnected;
	}

	/**
	 * Disconnect the LAN IP Printer
	 */
	@Override
	public boolean disconnect() {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * Check the connection is connected or not
	 * @return true if connected, false otherwise
	 */
	@Override
	public boolean isConnected() {
		return isConnected;
	}

	/**
	 * set the time (in second) for the connection timeout.
	 */
	@Override
	public void setTimeout(int time) {
		timeout = time;		
	}
	
	private void createSocket(){
		this.printerSocket = new Socket();
	}

	private void connect(SocketAddress address) throws IOException{
		printerSocket.connect(address, timeout * 1000);
		setConnected( true );
	}
	
	private void setConnected(boolean isConnected){
		this.isConnected = isConnected;
	}
}
